package com.xuxu.product.service.impl;

import com.alibaba.fastjson.JSON;
import com.xuxu.product.entity.ProductEntity;
import com.xuxu.product.service.ElasticService;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.TermQueryBuilder;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @className: ElasticServiceImpl
 * @author: Maxuxu
 * @date: 2022/8/18 9:38
 * @description: elasticsearch的接口实现类
 */
@Service("elasticService")
public class ElasticServiceImpl implements ElasticService {

    @Autowired
    private RestHighLevelClient client;


    @Override
    public void addManyDocum() throws IOException {

    }

    @Override
    public void addDocum(ProductEntity product, String docId) throws IOException {
        IndexRequest request = new IndexRequest("product");
        // 设置文档id
        request.id(docId);
        // 设置超时时间为 1s
        request.timeout(TimeValue.timeValueMillis(1000));
        // 将数据放入请求中
        request.source(JSON.toJSONString(product), XContentType.JSON);
        // 发送请求，获取相应结果
        IndexResponse response = client.index(request, RequestOptions.DEFAULT);
        // 获取建立索引的状态信息 CREATED
        System.out.println(response.status());
        // 返回创建成功的内容信息
        System.out.println(response);
    }

    @Override
    public void searchPage(String name, Integer index, Integer size) throws IOException {
        // 1. 创建查询请求对象
        SearchRequest searchRequest = new SearchRequest("product");
        // 2. 构造搜索条件
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        //  2-1. 查询条件，使用QueryBuilders 工具类创建
        TermQueryBuilder termQueryBuilder = QueryBuilders.termQuery("pname", name);
        //  2-2. 设置高亮
        searchSourceBuilder.highlighter(new HighlightBuilder());
        //  2-3. 分页
        searchSourceBuilder.from(index);
        searchSourceBuilder.size(size);
        // 设置超时时间
        searchSourceBuilder.timeout(new TimeValue(60, TimeUnit.SECONDS));
        //  2-4. 投入条件
        searchSourceBuilder.query(termQueryBuilder);
        // 3. 添加条件到请求
        searchRequest.source(searchSourceBuilder);
        // 4. 客户端查询请求
        SearchResponse search = client.search(searchRequest, RequestOptions.DEFAULT);
        // 5. 返回结果
        SearchHits hits = search.getHits();
        System.out.println(JSON.toJSONString(hits));
        for (SearchHit documentFields : hits.getHits()) {
            System.out.println(documentFields.getSourceAsMap());
        }
    }

    @Override
    public List<Map<String, Object>> highLightSearch(String keyword, Integer pageindex, Integer pageSize) throws IOException {
        SearchRequest searchRequest = new SearchRequest("product");
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        // 精确查询，添加查询条件
        TermQueryBuilder termQueryBuilder = QueryBuilders.termQuery("pname", keyword);
        searchSourceBuilder.timeout(new TimeValue(60, TimeUnit.SECONDS));
        searchSourceBuilder.query(termQueryBuilder);
        // 分页
        searchSourceBuilder.from(pageindex);
        searchSourceBuilder.size(pageSize);
        // 高亮 =========
        HighlightBuilder highlightBuilder = new HighlightBuilder();
        highlightBuilder.field("pname");
        highlightBuilder.preTags("<span style='color:red'>");
        highlightBuilder.postTags("</span>");
        searchSourceBuilder.highlighter(highlightBuilder);
        // 执行查询
        searchRequest.source(searchSourceBuilder);
        SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);
        // 解析结果 ==========
        SearchHits hits = searchResponse.getHits();
        List<Map<String, Object>> results = new ArrayList<>();
        for (SearchHit documentFields : hits.getHits()) {
            // 使用新的字段值（高亮），覆盖旧的字段值
            Map<String, Object> sourceAsMap = documentFields.getSourceAsMap();
            // 高亮字段
            Map<String, HighlightField> highlightFields = documentFields.getHighlightFields();
            HighlightField name = highlightFields.get("pname");
            // 替换
            if (name != null) {
                Text[] fragments = name.fragments();
                StringBuilder new_name = new StringBuilder();
                for (Text text : fragments) {
                    new_name.append(text);
                }
                sourceAsMap.put("pname", new_name.toString());
            }
            results.add(sourceAsMap);
        }
        return results;
    }

}
